package com.xinlang.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;

public class VectorLoader
{
  static Pattern patternIdValue = Pattern.compile("^\\s*(\\d+):([0-9\\.]+)\\s*$");

  public List<Vector> load(String filename)
    throws IOException
  {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));

    int cardinality = Integer.valueOf(reader.readLine()).intValue();
    List<Vector> vectors = new ArrayList<Vector>();
    String line;
    while ((line = reader.readLine()) != null)
    {
      vectors.add(parseVector(cardinality, line));
    }
    reader.close();

    return vectors;
  }

  static Vector parseVector(int cardinality, String line)
  {
    String[] items = line.split(" ");
    Vector vec = new RandomAccessSparseVector(cardinality);
    for (int i = 1; i < items.length; ++i) {
      Matcher matcher = patternIdValue.matcher(items[i]);
      if (matcher.matches()) {
        int index = Integer.valueOf(matcher.group(1)).intValue();
        double value = Double.valueOf(matcher.group(2)).doubleValue();

        vec.set(index, value);
      }
    }
    return vec;
  }

  public static void main(String[] args)
    throws IOException
  {
    VectorLoader loader = new VectorLoader();
    List<Vector> vectors = loader.load("jiaduobao1_2k.mat");
    PrintStream out = new PrintStream("dump.txt");
    for (Vector vec : vectors) {
      out.println(vec);
    }
    out.close();
  }
}